package inftel.android;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ComentariosAdapter extends SimpleAdapter{

	private List<Comentario> listaComentarios;

	
	public ComentariosAdapter(List<Comentario> lista,Context context, List<? extends Map<String, ?>> data,
		int resource, String[] from, int[] to) {
		super(context, data, resource, from, to);
		this.listaComentarios = lista;
		
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v = super.getView(position, convertView, parent);
		//Log.i("ENTRANDO",String.valueOf(position));
		View autorView = v.findViewById(R.id.fila_comentarios_listitem_autor);
		String autor = ((TextView) autorView).getText().toString();
		View mensajeView = v.findViewById(R.id.fila_comentarios_listitem_mensaje);
		String mensaje = ((TextView) mensajeView).getText().toString();
		Iterator<Comentario> iter = getComentarios().iterator();
		//Log.i("Iterando","Cargando " + listaComentarios.size() + " Comentarios");

			while(iter.hasNext()){
				Comentario c = iter.next();
				String enlaceFoto = c.getFotoPerfil();
				View imagen = v.findViewById(R.id.fila_comentarios_listitem_pic);
				Log.i("Adaptador","Escalando imagen");
			    Bitmap bm = Bitmap.createScaledBitmap(getBitmapFromURL(enlaceFoto),48,48,true);
				((ImageView)imagen).setImageBitmap(bm);
			}
		return v;
	}
	public List<Comentario> getComentarios() {
		return listaComentarios;
	}

	public void setListaComentarios(List<Comentario> listaComentarios) {
		this.listaComentarios = listaComentarios;
	}
		
	public Bitmap getBitmapFromURL(String src) {
		
		Bitmap bm = null; 
	    try {
	        URL url = new URL(src);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoInput(true);
	        connection.connect();
	        InputStream input = connection.getInputStream();
	        Bitmap myBitmap = BitmapFactory.decodeStream(input);	        
	        bm = myBitmap;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
	    return bm;
	}
}

